import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { h, onMounted, reactive, ref } from "vue";
import type { FormItemProps } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, deviceDetection, isAllEmpty } from "@pureadmin/utils";
import { http } from "@/utils/http";
import { flattenData } from "@/utils/libs";
import { changeHttpLink } from "@/utils/test";

export function useMenu() {
  const form = reactive({
    title: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const cloneDataList = ref([]); //缓存未处理的原始数据
  const loading = ref(true);

  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "菜单" : "primary";
      case 1:
        return text ? "iframe" : "warning";
      case 2:
        return text ? "按钮" : "danger";
    }
  };

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "Title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.Icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{row.Title}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "MenuType",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getMenuType(row.MenuType)}
          effect="plain"
        >
          {getMenuType(row.MenuType, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "Path"
    },
    {
      label: "组件路径",
      prop: "Component",
      formatter: ({ Path, Component }) =>
        isAllEmpty(Component) ? Path : Component
    },
    {
      label: "权限标识",
      prop: "Auths"
    },
    {
      label: "排序",
      prop: "Rank",
      width: 100
    },
    {
      label: "隐藏",
      prop: "ShowLink",
      formatter: ({ ShowLink }) => (ShowLink ? "否" : "是"),
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    http
      .get(changeHttpLink("/api/System/menu_list"))
      .then((res: any) => {
        // 返回格式要求：唯一id加父节点parentId，parentId取父节点id
        if (res.Data != null) {
          let newData = res.Data;
          if (!isAllEmpty(form.title)) {
            // 前端搜索菜单名称
            newData = newData.filter((item: any) =>
              item.Title.includes(form.title)
            );
          }
          cloneDataList.value = cloneDeep(newData);
          dataList.value = handleTree(newData, "Id", "ParentId"); // 处理成树结构
        }
        setTimeout(() => {
          loading.value = false;
        }, 300);
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  function formatHigherMenuOptions(treeList: any[], id: any) {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].Id == id;
      formatHigherMenuOptions(treeList[i].children, id);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id,
          menuType: row?.MenuType ?? 0,
          higherMenuOptions: formatHigherMenuOptions(
            cloneDeep(dataList.value),
            id
          ),
          parentId: row?.ParentId ?? 0,
          title: row?.Title ?? "",
          name: row?.Name ?? "",
          path: row?.Path ?? "",
          component: row?.Component ?? "",
          rank: row?.Rank ?? dataList.value.length + 1,
          redirect: row?.Redirect ?? "",
          icon: row?.Icon ?? "",
          auths: row?.Auths ?? "",
          frameSrc: row?.FrameSrc ?? "",
          showLink: row?.ShowLink ?? true,
          showParent: row?.ShowParent ?? true
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了菜单名称为【${curData.title}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            const formData = {
              Id: 0,
              MenuType: curData.menuType,
              ParentId: curData?.parentId ?? 0,
              Title: curData?.title ?? "",
              Name: curData?.name ?? "",
              Path: curData?.path ?? "",
              Component: curData?.component ?? "",
              Rank: parseInt(curData.rank),
              Redirect: curData?.redirect ?? "",
              Icon: curData?.icon ?? "",
              Auths: curData?.auths ?? "",
              FrameSrc: curData?.frameSrc ?? "",
              ShowLink: curData.showLink,
              ShowParent: curData.showParent
            };
            if (title !== "新增") {
              formData.Id = curData.id;
            }
            http
              .post(changeHttpLink("/api/System/menu_edit"), {
                data: formData
              })
              .then((res: any) => {
                if (res.Success) {
                  chores();
                } else {
                  message(res.Message, { type: "error" });
                }
              })
              .catch(err => {
                message(err.message, { type: "error" });
              });
          }
        });
      }
    });
  }

  function handleDelete(row) {
    const listChildren = flattenData(row);
    const findIds = listChildren.map(item => {
      return item.Id;
    });
    http
      .post(changeHttpLink("/api/System/menu_remove"), {
        data: {
          listIds: findIds
        }
      })
      .then((res: any) => {
        if (res.Success) {
          message(`您删除了菜单名称为【${row.Title}】的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange
  };
}
